"""
对话管理器
管理对话历史、系统提示词等
"""

import json
import logging
from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime

from config.config_manager import AppConfig

logger = logging.getLogger(__name__)


class ConversationManager:
    """对话管理器"""
    
    def __init__(self, config: AppConfig):
        self.config = config
        self.conversation_config = config.conversation
        self.system_prompt = config.llm.system_prompt
        self.max_history = self.conversation_config.max_history
        self.save_to_file = self.conversation_config.save_to_file
        self.history_file = self.conversation_config.history_file
        
        # 对话历史存储
        self.conversations: Dict[str, List[Dict[str, Any]]] = {}
        
        # 如果需要保存到文件，创建目录
        if self.save_to_file:
            Path(self.history_file).parent.mkdir(parents=True, exist_ok=True)
            self._load_history()
    
    def get_conversation(self, session_id: str = "default") -> List[Dict[str, Any]]:
        """获取对话历史"""
        if session_id not in self.conversations:
            self.conversations[session_id] = []
            # 添加系统提示词
            if self.system_prompt:
                self.conversations[session_id].append({
                    "role": "system",
                    "content": self.system_prompt
                })
        
        return self.conversations[session_id]
    
    def add_message(self, session_id: str, role: str, content: str, **kwargs):
        """添加消息到对话历史"""
        conversation = self.get_conversation(session_id)
        
        message = {
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat(),
            **kwargs
        }
        
        conversation.append(message)
        
        # 限制历史长度（保留系统提示词）
        system_messages = [msg for msg in conversation if msg["role"] == "system"]
        other_messages = [msg for msg in conversation if msg["role"] != "system"]
        
        if len(other_messages) > self.max_history:
            # 保留最新的消息
            other_messages = other_messages[-self.max_history:]
        
        self.conversations[session_id] = system_messages + other_messages
        
        # 保存到文件
        if self.save_to_file:
            self._save_history()
        
        logger.debug(f"添加消息到会话 {session_id}: {role} - {content[:50]}...")
    
    def add_user_message(self, session_id: str, content: str):
        """添加用户消息"""
        self.add_message(session_id, "user", content)
    
    def add_assistant_message(self, session_id: str, content: str, **kwargs):
        """添加助手消息"""
        self.add_message(session_id, "assistant", content, **kwargs)
    
    def add_tool_message(self, session_id: str, tool_call_id: str, content: str):
        """添加工具调用结果消息"""
        self.add_message(session_id, "tool", content, tool_call_id=tool_call_id)
    
    def clear_conversation(self, session_id: str = "default"):
        """清空对话历史"""
        if session_id in self.conversations:
            del self.conversations[session_id]
        
        # 重新初始化（会添加系统提示词）
        self.get_conversation(session_id)
        
        if self.save_to_file:
            self._save_history()
        
        logger.info(f"已清空会话 {session_id} 的对话历史")
    
    def get_messages_for_api(self, session_id: str = "default") -> List[Dict[str, Any]]:
        """获取用于API调用的消息格式"""
        conversation = self.get_conversation(session_id)
        
        # 转换为API需要的格式，移除时间戳等额外字段
        api_messages = []
        for msg in conversation:
            api_msg = {
                "role": msg["role"],
                "content": msg["content"]
            }
            
            # 保留工具调用相关字段
            if "tool_calls" in msg:
                api_msg["tool_calls"] = msg["tool_calls"]
            if "tool_call_id" in msg:
                api_msg["tool_call_id"] = msg["tool_call_id"]
            
            api_messages.append(api_msg)
        
        return api_messages
    
    def update_last_assistant_message(self, session_id: str, content: str, **kwargs):
        """更新最后一条助手消息（用于流式响应）"""
        conversation = self.get_conversation(session_id)
        
        # 找到最后一条助手消息
        for i in range(len(conversation) - 1, -1, -1):
            if conversation[i]["role"] == "assistant":
                conversation[i]["content"] = content
                conversation[i]["timestamp"] = datetime.now().isoformat()
                # 更新其他字段
                for key, value in kwargs.items():
                    conversation[i][key] = value
                break
        else:
            # 如果没找到助手消息，添加新的
            self.add_assistant_message(session_id, content, **kwargs)
        
        if self.save_to_file:
            self._save_history()
    
    def get_conversation_summary(self, session_id: str = "default") -> Dict[str, Any]:
        """获取对话摘要信息"""
        conversation = self.get_conversation(session_id)
        
        user_messages = [msg for msg in conversation if msg["role"] == "user"]
        assistant_messages = [msg for msg in conversation if msg["role"] == "assistant"]
        tool_messages = [msg for msg in conversation if msg["role"] == "tool"]
        
        return {
            "session_id": session_id,
            "total_messages": len(conversation),
            "user_messages": len(user_messages),
            "assistant_messages": len(assistant_messages),
            "tool_messages": len(tool_messages),
            "has_system_prompt": any(msg["role"] == "system" for msg in conversation),
            "last_message_time": conversation[-1].get("timestamp") if conversation else None
        }
    
    def _load_history(self):
        """从文件加载对话历史"""
        try:
            if Path(self.history_file).exists():
                with open(self.history_file, 'r', encoding='utf-8') as f:
                    self.conversations = json.load(f)
                logger.info(f"已从文件加载对话历史: {self.history_file}")
        except Exception as e:
            logger.error(f"加载对话历史失败: {e}")
            self.conversations = {}
    
    def _save_history(self):
        """保存对话历史到文件"""
        try:
            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump(self.conversations, f, ensure_ascii=False, indent=2)
            logger.debug(f"对话历史已保存到: {self.history_file}")
        except Exception as e:
            logger.error(f"保存对话历史失败: {e}")
    
    def list_sessions(self) -> List[str]:
        """列出所有会话ID"""
        return list(self.conversations.keys())
    
    def delete_session(self, session_id: str):
        """删除指定会话"""
        if session_id in self.conversations:
            del self.conversations[session_id]
            if self.save_to_file:
                self._save_history()
            logger.info(f"已删除会话: {session_id}")
        else:
            logger.warning(f"会话不存在: {session_id}")
